<template>
  <div class="order-detail-container">
    <div class="page-header">
      <el-page-header @back="goBack" :title="`订单详情：${orderData.orderNo || ''}`" />
    </div>

    <el-card v-loading="loading" class="detail-card">
      <template #header>
        <div class="card-header">
          <span>订单信息</span>
          <div>
            <el-button 
              v-if="orderData.status === 1" 
              type="primary" 
              @click="handleShipOrder"
              size="small"
            >
              发货
            </el-button>
            <el-button 
              v-if="orderData.status === 0" 
              type="danger" 
              @click="handleCancelOrder"
              size="small"
            >
              取消订单
            </el-button>
          </div>
        </div>
      </template>

      <el-descriptions :column="3" border>
        <el-descriptions-item label="订单编号">
          {{ orderData.orderNo }}
        </el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getOrderStatusType(orderData.status)">
            {{ getOrderStatusText(orderData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ orderData.createTime }}
        </el-descriptions-item>
        <el-descriptions-item label="支付时间">
          {{ orderData.payTime || '未支付' }}
        </el-descriptions-item>
        <el-descriptions-item label="发货时间">
          {{ orderData.deliveryTime || '未发货' }}
        </el-descriptions-item>
        <el-descriptions-item label="收货时间">
          {{ orderData.receiveTime || '未收货' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span>收货信息</span>
        </div>
      </template>

      <el-descriptions :column="2" border v-if="orderData.addressSnapshot">
        <el-descriptions-item label="收货人">
          {{ orderData.addressSnapshot?.receiver }}
        </el-descriptions-item>
        <el-descriptions-item label="联系电话">
          {{ orderData.addressSnapshot?.phone }}
        </el-descriptions-item>
        <el-descriptions-item label="收货地址" :span="2">
          {{ formatAddress(orderData.addressSnapshot) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span>商品信息</span>
        </div>
      </template>

      <el-table :data="orderData.items || []" border>
        <el-table-column label="商品图片" width="100">
          <template #default="scope">
            <el-image 
              style="width: 50px; height: 50px" 
              :src="scope.row.productSnapshot?.cover"
              fit="cover"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="productSnapshot.name" label="商品名称" />
        <el-table-column prop="price" label="单价" width="100">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="100" />
        <el-table-column prop="totalAmount" label="小计" width="120">
          <template #default="scope">
            ¥{{ scope.row.totalAmount }}
          </template>
        </el-table-column>
      </el-table>

      <div class="order-amount">
        <div class="amount-item">
          <span>商品总价：</span>
          <span class="price">¥{{ orderData.totalAmount || 0 }}</span>
        </div>
        <div class="amount-item">
          <span>运费：</span>
          <span class="price">¥{{ orderData.freightAmount || 0 }}</span>
        </div>
        <div class="amount-item">
          <span>实付金额：</span>
          <span class="price highlight">¥{{ orderData.payAmount || 0 }}</span>
        </div>
      </div>
    </el-card>

    <!-- 发货对话框 -->
    <el-dialog
      v-model="shipDialogVisible"
      title="订单发货"
      width="500px"
    >
      <el-form :model="shipForm" label-width="100px">
        <el-form-item label="快递公司">
          <el-input v-model="shipForm.expressCompany" placeholder="请输入快递公司"></el-input>
        </el-form-item>
        <el-form-item label="快递单号">
          <el-input v-model="shipForm.expressNo" placeholder="请输入快递单号"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shipDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShip">确认发货</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrderDetail, updateOrderStatus } from '@/api/order'
import { getOrderStatusType, getOrderStatusText } from '@/utils/format'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const orderData = ref({})
const shipDialogVisible = ref(false)
const shipForm = ref({
  expressCompany: '',
  expressNo: ''
})

// 返回上一页
const goBack = () => {
  router.back()
}

// 获取订单详情
const fetchOrderDetail = async () => {
  const orderId = route.params.id
  if (!orderId) {
    ElMessage.error('订单ID不能为空')
    return
  }

  loading.value = true
  try {
    const res = await getOrderDetail(orderId)
    orderData.value = res.data
  } catch (error) {
    ElMessage.error('获取订单详情失败')
  } finally {
    loading.value = false
  }
}

// 显示发货对话框
const handleShipOrder = () => {
  shipDialogVisible.value = true
}

// 确认发货
const confirmShip = async () => {
  if (!shipForm.value.expressCompany || !shipForm.value.expressNo) {
    ElMessage.warning('请填写完整的快递信息')
    return
  }

  try {
    await updateOrderStatus(orderData.value.id, { 
      status: 2, 
      expressCompany: shipForm.value.expressCompany,
      expressNo: shipForm.value.expressNo 
    })
    ElMessage.success('发货成功')
    shipDialogVisible.value = false
    fetchOrderDetail() // 刷新订单信息
  } catch (error) {
    ElMessage.error('发货失败')
  }
}

// 取消订单
const handleCancelOrder = () => {
  ElMessageBox.confirm('确认取消该订单?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await updateOrderStatus(orderData.value.id, { status: 4 })
      ElMessage.success('订单已取消')
      fetchOrderDetail() // 刷新订单信息
    } catch (error) {
      ElMessage.error('取消订单失败')
    }
  }).catch(() => {})
}

// 格式化地址
const formatAddress = (address) => {
  if (!address) return ''
  return `${address.province} ${address.city} ${address.district} ${address.detail}`
}

onMounted(() => {
  fetchOrderDetail()
})
</script>

<style scoped>
.order-detail-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.detail-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-amount {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.amount-item {
  margin-bottom: 10px;
}

.price {
  font-weight: bold;
  margin-left: 10px;
  min-width: 80px;
  display: inline-block;
  text-align: right;
}

.highlight {
  color: #f56c6c;
  font-size: 18px;
}
</style> 